﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace LowLevelGraphics
{
        public partial class Form1 : Form
        {
            Color cl;

            public Form1()
            {
                //InitializeComponent();
                DoubleBuffered = true;
            }

            private void tUpdate_Tick(object sender, EventArgs e)
            {
                Bitmap bmp = Core.GetDesktop();
                cl = bmp.GetPixel(Cursor.Position.X, Cursor.Position.Y);
                Refresh();
            }

            protected override void OnPaint(PaintEventArgs e)
            {
                e.Graphics.Clear(cl);
            }
        }

        public class Core
        {
            public static Bitmap GetDesktop()
            {
                int screenX;
                int screenY;
                IntPtr hBmp;
                IntPtr hdcScreen = CGraphics.GetDC(CGraphics.GetDesktopWindow());
                IntPtr hdcCompatible = CGraphics.CreateCompatibleDC(hdcScreen);

                screenX = CGraphics.GetSystemMetrics(0);
                screenY = CGraphics.GetSystemMetrics(1);
                hBmp = CGraphics.CreateCompatibleBitmap(hdcScreen, screenX, screenY);

                if (hBmp != IntPtr.Zero)
                {
                    IntPtr hOldBmp = (IntPtr)CGraphics.SelectObject(hdcCompatible, hBmp);
                    CGraphics.BitBlt(hdcCompatible, 0, 0, screenX, screenY, hdcScreen, 0, 0, 13369376);

                    CGraphics.SelectObject(hdcCompatible, hOldBmp);
                    CGraphics.DeleteDC(hdcCompatible);
                    CGraphics.ReleaseDC(CGraphics.GetDesktopWindow(), hdcScreen);

                    Bitmap bmp = System.Drawing.Image.FromHbitmap(hBmp);

                    CGraphics.DeleteObject(hBmp);
                    GC.Collect();

                    return bmp;
                }

                return null;
            }

            /// <summary>
            /// Get pixel color from Screen
            /// </summary>
            /// <returns></returns>
            public static Color GetPixelColorFromScreen()
            {
                Bitmap bmp = Core.GetDesktop();
                Color colorOfPixelFromScreen = bmp.GetPixel(Cursor.Position.X, Cursor.Position.Y);
                return colorOfPixelFromScreen;
            }
        }
    }

